<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="alternate" href="/atom.xml" title="el's blog" type="application/atom+xml">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"right","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="强缓存通过 Expires 或者 Cache-Control 两者实现，而协商缓存通过 Etag &amp; If-None-Match 或者 Last-Modified &amp; If-Modified-Since 实现的">
<meta property="og:type" content="article">
<meta property="og:title" content="浏览器强缓存与协商缓存">
<meta property="og:url" content="http:&#x2F;&#x2F;ever-lose.gitee.io&#x2F;2017&#x2F;03&#x2F;23&#x2F;tcp-http&#x2F;broswer-cache&#x2F;index.html">
<meta property="og:site_name" content="el&#39;s blog">
<meta property="og:description" content="强缓存通过 Expires 或者 Cache-Control 两者实现，而协商缓存通过 Etag &amp; If-None-Match 或者 Last-Modified &amp; If-Modified-Since 实现的">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http:&#x2F;&#x2F;img.souche.com&#x2F;20170322&#x2F;png&#x2F;b2b1d73c5b37bf60d72594ea2ee044d3.png">
<meta property="og:image" content="http:&#x2F;&#x2F;img.souche.com&#x2F;20170323&#x2F;png&#x2F;93845cf76c9ae637c201da4318243ab8.png">
<meta property="og:image" content="http:&#x2F;&#x2F;img.souche.com&#x2F;20170323&#x2F;png&#x2F;60a65ccb2dcc8ed1cf372405f811c987.png">
<meta property="og:updated_time" content="2019-11-08T06:19:30.963Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;img.souche.com&#x2F;20170322&#x2F;png&#x2F;b2b1d73c5b37bf60d72594ea2ee044d3.png">

<link rel="canonical" href="http://ever-lose.gitee.io/2017/03/23/tcp-http/broswer-cache/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>浏览器强缓存与协商缓存 | el's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">el's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">everlose's blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://ever-lose.gitee.io/2017/03/23/tcp-http/broswer-cache/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpeg">
      <meta itemprop="name" content="everlose">
      <meta itemprop="description" content="focus on Js、CSS、Node...etc">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="el's blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          浏览器强缓存与协商缓存
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-03-23 00:00:00" itemprop="dateCreated datePublished" datetime="2017-03-23T00:00:00+08:00">2017-03-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-11-08 14:19:30" itemprop="dateModified" datetime="2019-11-08T14:19:30+08:00">2019-11-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/tcp-http/" itemprop="url" rel="index">
                    <span itemprop="name">tcp-http</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">强缓存通过 Expires 或者 Cache-Control 两者实现，而协商缓存通过 Etag & If-None-Match 或者 Last-Modified & If-Modified-Since 实现的</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="基本认知"><a href="#基本认知" class="headerlink" title="基本认知"></a>基本认知</h2><p>浏览器缓存分为强缓存和协商缓存： </p>
<ol>
<li><p>浏览器在加载资源时，先根据这个资源的一些http header判断它是否命中强缓存，强缓存如果命中，浏览器直接从自己的缓存中读取资源，不会发请求到服务器，此请求返回的http状态为200，在chrome的开发者工具的network里面size会显示为from cache。</p>
</li>
<li><p>当强缓存没有命中的时候，浏览器一定会发送一个请求到服务器，通过服务器端依据资源的另外一些http header验证这个资源是否命中协商缓存，如果协商缓存命中，服务器会将这个请求返回，并且状态码为304，不会返回这个资源的数据，而是告诉客户端可以直接从缓存中加载这个资源，于是浏览器就又会从自己的缓存中去加载这个资源；</p>
</li>
<li><p>当协商缓存也没有命中的时候，浏览器直接从服务器加载资源数据。</p>
</li>
</ol>
<p>强缓存与协商缓存的共同点是：如果命中，都是从客户端缓存中加载资源，而不是从服务器加载资源数据；区别是：强缓存不发请求到服务器，协商缓存会发请求到服务器。</p>
<h2 id="强缓存原理"><a href="#强缓存原理" class="headerlink" title="强缓存原理"></a>强缓存原理</h2><p>强缓存是利用Expires或者Cache-Control这两个http response header实现的，它们都用来表示资源在客户端缓存的有效期。Expires是http1.0提出的一个表示资源过期时间的header，而Cache-Control则是http1.1提出的，如果同时存在则以Cache-Control为先。如下图</p>
<p><img src="http://img.souche.com/20170322/png/b2b1d73c5b37bf60d72594ea2ee044d3.png" alt=""></p>
<p><code>Expires:Sat, 01 Apr 2017 15:53:40 GMT</code>其实意味着在东八区2017/04/01 23:53:40的时候此资源过期。而<code>Cache-Control:max-age=864000</code>意味着从<code>Date:Wed, 22 Mar 2017 15:53:40 GMT</code>这个日期开始算往后10天则资源过期，这个时间在这里实际上就等同于Expires的时间。</p>
<p>Expires是较老的强缓存管理header，由于它是服务器返回的一个绝对时间，在服务器时间与客户端时间相差较大时，缓存管理容易出现问题，比如随意修改下客户端时间，就能影响缓存命中的结果。而Cache-Control是相对时间就不会有这种问题，两个请求头都加上也是为了兼容不支持http1.1的终端或者路由器。</p>
<h2 id="协商缓存原理"><a href="#协商缓存原理" class="headerlink" title="协商缓存原理"></a>协商缓存原理</h2><p>当浏览器对某个资源的请求没有命中强缓存，就会发一个请求到服务器，验证协商缓存是否命中，如果协商缓存命中，请求响应返回的http状态为304并且会显示一个Not Modified的字符串，并且让浏览器就又从自己的缓存中去加载这个资源。</p>
<p>协商缓存是利用的是【Last-Modified，If-Modified-Since】和【ETag、If-None-Match】这两对Header来管理的。</p>
<h3 id="Last-Modified，If-Modified-Since"><a href="#Last-Modified，If-Modified-Since" class="headerlink" title="Last-Modified，If-Modified-Since"></a>Last-Modified，If-Modified-Since</h3><p><img src="http://img.souche.com/20170323/png/93845cf76c9ae637c201da4318243ab8.png" alt=""></p>
<ol>
<li>浏览器第一次跟服务器请求一个资源，服务器在返回这个资源的同时，在respone的header加上Last-Modified的header，这个header表示这个资源在服务器上的最后修改时间</li>
<li>浏览器再次跟服务器请求这个资源时，在request的header上加上If-Modified-Since的header，这个header的值就是上一次请求时返回的Last-Modified的值</li>
<li>服务器再次收到资源请求时，根据浏览器传过来If-Modified-Since和资源在服务器上的最后修改时间判断资源是否有变化，如果没有变化则返回304 Not Modified，但是不会返回资源内容；如果有变化，就正常返回资源内容。当服务器返回304 Not Modified的响应时，response header中不会再添加Last-Modified的header，因为既然资源没有变化，那么Last-Modified也就不会改变</li>
</ol>
<p>如果协商缓存没有命中，浏览器直接从服务器加载资源时，Last-Modified Header在重新加载的时候会被更新，下次请求时，If-Modified-Since会启用上次返回的Last-Modified值。</p>
<p>有时候也会服务器上资源其实有变化，但是最后修改时间却没有变化的情况，就会影响协商缓存的可靠性。所以就有了另外一对header来管理协商缓存，这对header就是【ETag、If-None-Match】</p>
<h3 id="ETag和If-None-Match"><a href="#ETag和If-None-Match" class="headerlink" title="ETag和If-None-Match"></a>ETag和If-None-Match</h3><p><img src="http://img.souche.com/20170323/png/60a65ccb2dcc8ed1cf372405f811c987.png" alt=""></p>
<p>浏览器第一次跟服务器请求一个资源，会在respone的header加上ETag响应头，这是服务器根据当前请求的资源生成的一个唯一标识，只要资源有变化这个串就不同，只要资源有变化这个串就不同，跟最后修改时间没有关系，所以能很好的补充Last-Modified的问题</p>
<p>浏览器再次跟服务器请求这个资源时，在request的header上加上If-None-Match的header，这个header的值就是上一次请求时返回的ETag的值。</p>
<p>服务器再次收到资源请求时，根据浏览器传过来If-None-Match和然后再根据资源生成一个新的ETag，如果这两个值相同就说明资源没有变化，否则就是有变化；如果没有变化则返回304 Not Modified，但是不会返回资源内容；如果有变化，就正常返回资源内容。与Last-Modified不一样的是，当服务器返回304 Not Modified的响应时，由于ETag重新生成过，response header中还会把这个ETag返回，即使这个ETag跟之前的没有变化</p>
<h2 id="缓存管理"><a href="#缓存管理" class="headerlink" title="缓存管理"></a>缓存管理</h2><p>协商缓存需要配合强缓存使用，你看前面这个截图中，除了Last-Modified这个header，还有强缓存的相关header，因为如果不启用强缓存的话，协商缓存根本没有意义。</p>
<p>如果资源已经被浏览器缓存下来，在缓存失效之前，再次请求时，默认会先检查是否命中强缓存，如果强缓存命中则直接读取缓存，如果强缓存没有命中则发请求到服务器检查是否命中协商缓存，如果协商缓存命中，则告诉浏览器还是可以从缓存读取，否则才从服务器返回最新的资源。这是默认的处理方式，这个方式可能被浏览器的行为改变：</p>
<ul>
<li>当win上ctrl+f5、mac上command+shift+R来强制刷新网页时，直接从服务器加载，跳过强缓存和协商缓存；</li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p><a href="http://www.cnblogs.com/lyzg/p/5125934.html" target="_blank" rel="noopener">流云诸葛的浏览器缓存知识小结及应用</a></p>

    </div>

    
    
    

      <footer class="post-footer">

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/2017/03/16/css/flex-practice/" rel="next" title="CSS flex布局实践">
                  <i class="fa fa-chevron-left"></i> CSS flex布局实践
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
                <a href="/2017/03/23/tcp-http/dns-introduce/" rel="prev" title="DNS 科普文">
                  DNS 科普文 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          
    <div class="comments" id="gitalk-container"></div>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#基本认知"><span class="nav-number">1.</span> <span class="nav-text">基本认知</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#强缓存原理"><span class="nav-number">2.</span> <span class="nav-text">强缓存原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#协商缓存原理"><span class="nav-number">3.</span> <span class="nav-text">协商缓存原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Last-Modified，If-Modified-Since"><span class="nav-number">3.1.</span> <span class="nav-text">Last-Modified，If-Modified-Since</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ETag和If-None-Match"><span class="nav-number">3.2.</span> <span class="nav-text">ETag和If-None-Match</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缓存管理"><span class="nav-number">4.</span> <span class="nav-text">缓存管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">5.</span> <span class="nav-text">参考</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="everlose"
    src="/images/avatar.jpeg">
  <p class="site-author-name" itemprop="name">everlose</p>
  <div class="site-description" itemprop="description">focus on Js、CSS、Node...etc</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">97</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/everlose" title="GitHub &amp;rarr; https:&#x2F;&#x2F;github.com&#x2F;everlose" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:ever-lose@foxmail.com" title="E-Mail &amp;rarr; mailto:ever-lose@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">everlose</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v7.5.0
  </div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/muse.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>













  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: '48fe7d5cb2ac7e2c7fbf',
      clientSecret: '8f67b574218201d3b3ec6efe69276902e711e655',
      repo: 'everlose-blog',
      owner: 'everlose',
      admin: [''],
      id: '78a1704c60b089b1dc0b3f8ec263ed49',
        language: 'zh-CN',
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
